package controllers

import (
	"context"
	"errors"
	"github.com/gin-gonic/gin"
	"go.didapinche.com/foundation/plat-echo/app/ops/models"
	"go.didapinche.com/foundation/plat-echo/app/ops/services"
	"go.didapinche.com/foundation/plat-echo/pkg/constants"
	"go.didapinche.com/uic"
	"go.uber.org/zap"
	"net/http"
)

type AccessRecordController struct {
	accessRecordService services.AccessRecordService
	logger              *zap.Logger
}

func NewAccessRecordController(accessRecordService services.AccessRecordService, logger *zap.Logger) *AccessRecordController {
	return &AccessRecordController{
		accessRecordService: accessRecordService,
		logger:              logger.With(zap.String("type", "controller.access_record")),
	}
}

//查询最近访问
func (a *AccessRecordController) Find(c *gin.Context) {
	params := new(struct {
		PageNum  int                    `form:"page_num"`
		PageSize int                    `form:"page_size"`
		Type     models.AccessGraphType `form:"type"`
		Name     string                 `form:"name"`
	})
	if err := c.BindQuery(params); err != nil {
		c.String(http.StatusBadRequest, "bind params error:%v", err)
		a.logger.Error("bind params error", zap.Error(err))
		return
	}
	if params.PageNum == 0 {
		params.PageNum = 1
	}
	if params.PageSize == 0 {
		params.PageSize = 10
	}
	uid := c.GetString(uic.KeyUserID)
	record, total, err := a.accessRecordService.FindByUID(c.Request.Context(), uid, params.Type, params.Name, params.PageNum, params.PageSize)
	if err != nil {
		if errors.Is(err, context.Canceled) {
			a.logger.Error("context canceled", zap.Error(err))
			c.Status(constants.StatusRequestCanceled)
			return
		}
		a.logger.Error("call accessRecordService.FindByUID() error", zap.Error(err))
		c.String(http.StatusInternalServerError, "call accessRecordService.FindByUID() error:%v", err)
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"data":        record,
		"total_count": total,
	})
}
